package com.wthink.hzgj.util

import java.nio.ByteBuffer
import java.nio.charset.Charset

fun ByteBuffer.readString(len: Int? = null, charset: Charset = Charset.forName("GB2312")): String {
    if (len != null) {
        val data = ByteArray(len)
        this.get(data)
        return data.toString(charset)
    }

    this.mark()
    var size = 0
    val end = 0.toByte()
    while (true) {
        val value = this.get()
        size++
        if (value == end) {
            break
        }
    }

    this.reset()
    val data = ByteArray(size)

    this.get(data)

    return data.sliceArray(IntRange(0, data.size - 2)).toString(charset)
}

fun ByteBuffer.readBCD(size: Int): String {
    val data = ByteArray(size)
    this.get(data)

    return BCD.bcd2Str(data)
}